package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

/**
中间件 - 自定义
*/
func main() {
	r := gin.Default()

	r.Use(IPAuthMiddleware())

	r.GET("/test", func(c *gin.Context) {
		c.String(http.StatusOK, "hello test")
	})

	r.Run()
}

func IPAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		ipList := []string{
			"192.0.0.1",
		}
		flag := false

		clientIP := c.ClientIP()
		for _, ip := range ipList {
			if ip == clientIP {
				flag = true
				break
			}
		}

		if !flag {
			c.String(http.StatusUnauthorized, "%s, not in iplist", clientIP)
			c.Abort()
		}
	}
}
